﻿#include "CWebSocketClient.h"
#include <QBuffer>
#include "CInfoExchangeForRob.h"
#include <QThreadPool>
#include <QDebug>
#include <QThread>
#include <qtimer.h>
#include <qjsondocument.h>
#include <qjsonobject.h>
#include "CDevFollow.h"
#include "CInfoExchangeForSensor.h"

//WebSockek客户端
CWebSocketClient::CWebSocketClient(QObject *parent, QWebSocket *pWebSocket,QString sIp)
    : QObject(parent),m_pWebSocket(pWebSocket),m_sIp(sIp)
{
	qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
	m_pAutoCloseTimer = new QTimer(this);
	connect(m_pAutoCloseTimer, &QTimer::timeout, this, &CWebSocketClient::slotAutoClose);
}

//析构
CWebSocketClient::~CWebSocketClient()
{
	if (m_pWebSocket != nullptr)
	{
		m_pWebSocket->deleteLater();
	}
}

//关闭WebSocket客户端
void CWebSocketClient::closeWebSocketClient()
{
   
}

//判断传入的QWebSocket是否是是这个Client的
bool CWebSocketClient::judgeIsThisWebsocketClient(QWebSocket *pWebSocketTemp)
{
    if(m_pWebSocket == nullptr)
    {
        return false;
    }
    if(m_pWebSocket == pWebSocketTemp)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void CWebSocketClient::handleRequest(QString sMsg)
{
	//首先通过请求中不同的场景类型，创建不同的业务处理对象
	QJsonDocument doc = QJsonDocument::fromJson(sMsg.toUtf8());
	// 检查是否成功解析JSON
	if (!doc.isObject())
	{
		return;
	}

	QJsonObject jsonObj = doc.object();
	if (jsonObj.contains("sceneType"))
	{
		QString sSceneType = jsonObj["sceneType"].toString();
		if (sSceneType == "rob")
		{
			m_pInfoExchange = new CInfoExchangeForRob();
			m_pInfoExchange->m_sCtrIp = m_sIp;
			connect(m_pInfoExchange, &CInfoExchangeBase::sigSendRspMsgString, this, &CWebSocketClient::slotSendRspMsgString);
			connect(m_pInfoExchange, &CInfoExchangeBase::sigSendRspMsg, this, &CWebSocketClient::slotSendRspMsg);
			m_pInfoExchange->analyzeReqStringToQueue(sMsg);
			//加入线程池
			QThreadPool::globalInstance()->start(m_pInfoExchange);
		}
		else if (sSceneType == "sensor")
		{
			m_pInfoExchange = new CInfoExchangeForSensor();
			connect(m_pInfoExchange, &CInfoExchangeBase::sigSendRspMsgString, this, &CWebSocketClient::slotSendRspMsgString);
			m_pInfoExchange->analyzeReqStringToQueue(sMsg);
			//加入线程池
			QThreadPool::globalInstance()->start(m_pInfoExchange);
		}
	}
	else//默认是机器人场景
	{
		m_pInfoExchange = new CInfoExchangeForRob();
		m_pInfoExchange->m_sCtrIp = m_sIp;
		connect(m_pInfoExchange, &CInfoExchangeBase::sigSendRspMsgString, this, &CWebSocketClient::slotSendRspMsgString);
		connect(m_pInfoExchange, &CInfoExchangeBase::sigSendRspMsg, this, &CWebSocketClient::slotSendRspMsg);
		m_pInfoExchange->analyzeReqStringToQueue(sMsg);
		//加入线程池
		QThreadPool::globalInstance()->start(m_pInfoExchange);
	}
}

//发生响应数据
void CWebSocketClient::slotSendRspMsg(SRspDataParam stRspRaram)
{
	//设备未关注  此时进来的应该是急停 不进行操作
	if (false == CDevFollow::getInstance()->isExistFollow(stRspRaram.sRspGuid))
	{
		return;
	}

	//将结果下发至队列
	int nSize = m_qDevCtrQueue.size();
	/*数量大于100 留下最后一个*/
	if (nSize > 100)
	{
		SRspDataParam stRspParam = m_qDevCtrQueue.last();
		m_qDevCtrQueue.clear();
		m_qDevCtrQueue.enqueue(stRspParam);
	}

	//添加时间
	stRspRaram.sRspime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
	m_qDevCtrQueue.enqueue(stRspRaram);

	//未开启定时器则开启自动关闭定时器  单取消关注指令不触发定时器
	if (false == m_pAutoCloseTimer->isActive())
	{
		m_pAutoCloseTimer->start(def_autoCloseFollow);
	}
}

//发送响应数据字符串
void CWebSocketClient::slotSendRspMsgString(QString sRspMsgString)
{
	m_pWebSocket->sendTextMessage(sRspMsgString);
}

//自动取消关注线程
void CWebSocketClient::slotAutoClose()
{
	SRspDataParam stRspParam = m_qDevCtrQueue.last();
	//判断当前是否还在关注
	bool bIsFollow = CDevFollow::getInstance()->isExistFollow(stRspParam.sRspGuid);
	if (false == bIsFollow)
	{
		m_pAutoCloseTimer->stop();
		return;
	}

	//判断当前是否还是自己在控制
	SDevFollowParam stFollowParam = CDevFollow::getInstance()->getDevFollowParam(stRspParam.sRspGuid);
	if (m_sIp != stFollowParam.sCtrIp)
	{
		m_pAutoCloseTimer->stop();
		return;
	}


	if (true == m_qDevCtrQueue.isEmpty())
	{
		m_pAutoCloseTimer->stop();
	}
	else
	{
		QDateTime qCurrTime = QDateTime::currentDateTime();
		qint64 dDiffTime = qCurrTime.toMSecsSinceEpoch() - QDateTime::fromString(stRspParam.sRspime,"yyyy-MM-dd hh:mm:ss").toMSecsSinceEpoch();

		//最后一次的操作时间与当前时间相差 大于 设定时间 自动取消关注   60000ms -> 60s -> 1min
		if (dDiffTime >= def_autoCloseFollow)
		{
			/*取消关注*/
			CInfoExchangeForRob* pInfoExchange = new CInfoExchangeForRob();
			pInfoExchange->m_sCtrIp = m_sIp;
			stRspParam.nStatus = 401;
			stRspParam.sMsg = QString::fromLocal8Bit("长时间未操作!自动断开设备关注!");
			QString sErrMsg = "";
			pInfoExchange->createRspMsgString(stRspParam, sErrMsg);
			m_pWebSocket->sendTextMessage(sErrMsg);
			delete pInfoExchange;
			pInfoExchange = nullptr;

			CDevFollow::getInstance()->removeDevFollow(stRspParam.sRspGuid);
			
			m_pAutoCloseTimer->stop();
		}
	}

}
